var user = {};
var userDao = require('../dao/userDao');
var fs = require('fs');
var captchapng = require('captchapng');

user.getUserInfo = function (req,res) {

    var uid = req.headers.openid;
    if(!uid){
        res.send({code:1,info:'参数缺失'});
        return;
    }
    userDao.getUserById(uid,null,null,function (err,user) {
        if(err){
            res.send({code:1,info:'获取用户信息失败!'});
        }else {
            res.send({code:0,user:user});
        }
    });
};

/**
 * 用户推荐人个数(包括1和2级)
 * @param req
 * @param res
 */
user.getRefereeNum = function (req,res) {
    var uid = req.headers.openid;
    if(!uid){
        res.send({code:1,info:'参数缺失'});
        return;
    }
    userDao.getRefereeNum(uid,function (err,refNum) {
        if(err){
            res.send({code:1,info:'获取信息失败!'});
        }else {
            res.send({code:0,refNum:refNum});
        }
    });
};


/**
 * 用户一级推荐人信息
 * @param req
 * @param res
 */
user.getReferee1Info = function (req,res) {
    var uid = req.headers.openid;
    if(!uid){
        res.send({code:1,info:'参数缺失'});
        return;
    }
    userDao.getReferee1Info(uid,function (err,ref1) {
        if(err){
            res.send({code:1,info:'获取信息失败!'});
        }else {
            res.send({code:0,ref1Info:ref1});
        }
    });
};

/**
 * 用户二级推荐人信息
 * @param req
 * @param res
 */
user.getReferee2Info = function (req,res) {
    var uid = req.headers.openid;
    if(!uid){
        res.send({code:1,info:'参数缺失'});
        return;
    }
    userDao.getReferee2Info(uid,function (err,ref2) {
        if(err){
            res.send({code:1,info:'获取信息失败!'});
        }else {
            res.send({code:0,ref2Info:ref2});
        }
    });
};

/**
 * 提现记录
 * @param req
 * @param res
 */
user.getCashList = function (req,res) {
    var uid = req.headers.openid;
    if(!uid){
        res.send({code:1,info:'参数缺失'});
        return;
    }
    userDao.getCashList(uid,function (err,list) {
        if(err){
            res.send({code:1,info:'获取信息失败!'});
        }else {
            res.send({code:0,list:list});
        }
    });
};

user.testPost = function (req,res) {
    console.log('post param1 !!!!',req.body.param1);
    res.send({code:'post'});
};
user.testGet = function (req,res) {
    console.log('get param  !!!!',req.headers.param1);
    res.send({code:'get'});
};

/**
 * 佣金记录
 * @param req
 * @param res
 */
user.getPostList = function (req,res) {
    var uid = req.headers.openid;
    if(!uid){
        res.send({code:1,info:'参数缺失'});
        return;
    }
    userDao.getPostList(uid,function (err,list) {
        if(err){
            res.send({code:1,info:'获取信息失败!'});
        }else {
            res.send({code:0,list:list});
        }
    });
};

/**
 * 提取未提现佣金
 * @param req
 * @param res
 */
user.extractCoin = function (req,res) {
    var uid = req.headers.openid;
    if(!uid){
        res.send({code:1,info:'参数缺失'});
        return;
    }
    userDao.extractCoin(uid,function (err,totalCoin) {
        if(err){
            res.send({code:1,info:'提取佣金失败,请重试'});
        }else {
            if(totalCoin){
                userDao.increaseUserCoin(uid,totalCoin, function () {});
            }
            res.send({code:0,totalCoin:totalCoin});
        }
    });
};

/**
 * 管理员后台
 */

user.getAllUser = function (req,res) {
    var uid = req.headers.openid;
    if(!uid || (uid != 'o4AyEt_EpmY83VE17bCOJ-t8MIEg' && uid != 'o4AyEt2gypi_z981XBQzM5in0q_U')){
        res.send({code:1,info:'没有权限!'});
        return;
    }
    userDao.getAllUser(function (err,users) {
        if(err){
            res.send({code:1,info:'获取数据失败,请重试'});
        }else {
            res.send({code:0,users:users});
        }
    });
};

user.getUserOrders = function (req,res) {
    var uid = req.headers.openid;
    if(!uid || (uid != 'o4AyEt_EpmY83VE17bCOJ-t8MIEg' && uid != 'o4AyEt2gypi_z981XBQzM5in0q_U')){
        res.send({code:1,info:'没有权限!'});
        return;
    }
    userDao.getUserOrders(function (err,orders) {
        if(err){
            res.send({code:1,info:'获取数据失败,请重试'});
        }else {
            res.send({code:0,orders:orders});
        }
    });
};
user.getPostCash = function (req,res) {
    var uid = req.headers.openid;
    if(!uid || (uid != 'o4AyEt_EpmY83VE17bCOJ-t8MIEg' && uid != 'o4AyEt2gypi_z981XBQzM5in0q_U')){
        res.send({code:1,info:'没有权限!'});
        return;
    }
    userDao.getPostCash(function (err,lists) {
        if(err){
            res.send({code:1,info:'获取数据失败,请重试'});
        }else {
            res.send({code:0,lists:lists});
        }
    });
};

/************渠道管理****************/

user.getChannelWorth = function (req,res) {
    var channel = req.headers.channel;
    if(!channel){
        res.send({code:1,info:'没有权限!'});
        return;
    }
    userDao.getChannelWorth(channel, function (err,data) {
        if(err){
            res.send({code:1,info:'参数错误!'});
            return;
        }
        res.send({code:0,data:data});
    })
};

user.balanceChannel = function (req,res) {
    var channel = req.headers.channel;
    var openid = req.headers.openid;

    if(!channel || openid != 'o4AyEt_EpmY83VE17bCOJ-t8MIEg' && openid != 'o4AyEt2gypi_z981XBQzM5in0q_U'){
        res.send({code:1,info:'没有权限!'});
        return;
    }

    userDao.balanceChannel(channel,openid, function (err,data) {
        if(err){
            res.send({code:1,info:'参数错误!'});
            return;
        }
        res.send({code:0,data:data});
    })
};


user.listChannel = function (req,res) {
    var channel = req.headers.channel;
    var openid = req.headers.openid;
    var body = req.body;
    //console.log('body:%s openid:%s',JSON.stringify(body),openid);
    var coinNum = body.coinNum,coinValue = body.coinValue,orderNum = body.orderNum,cashNum = body.cashNum,dividedRmb = body.dividedRmb;
    if(!channel || openid != 'o4AyEt_EpmY83VE17bCOJ-t8MIEg' && openid != 'o4AyEt2gypi_z981XBQzM5in0q_U'){
        res.send({code:1,info:'没有权限!'});
        return;
    }

    userDao.listChannel(openid,channel,coinNum,coinValue,orderNum,cashNum,dividedRmb, function (err,data) {
        if(err){
            res.send({code:1,info:'参数错误!'});
            return;
        }
        res.send({code:0,data:data});
    })
};

user.listHistory = function (req,res) {
    var channel = req.headers.channel;

    if(!channel){
        res.send({code:1,info:'没有权限!'});
        return;
    }

    userDao.channelHistory(channel, function (err,data) {
        if(err){
            res.send({code:1,info:'参数错误!'});
            return;
        }
        res.send({code:0,data:data});
    });
};

user.getChannelUser = function (req,res) {
    var channel = req.headers.channel;
    if(!channel){
        res.send({code:1,info:'没有权限!'});
        return;
    }
    userDao.getChannelUser(channel, function (err,lists) {
        if(err){
            res.send({code:1,info:'参数错误!'});
            return;
        }
        res.send({code:0,lists:lists});
    })
};

user.getChannelOrders = function (req,res) {
    var channel = req.headers.channel;
    if(!channel){
        res.send({code:1,info:'没有权限!'});
        return;
    }
    userDao.getChannelOrders(channel, function (err,lists) {
        if(err){
            res.send({code:1,info:'参数错误!'});
            return;
        }
        res.send({code:0,lists:lists});
    })
};

user.getChannelCash = function (req,res) {
    var channel = req.headers.channel;
    if(!channel){
        res.send({code:1,info:'没有权限!'});
        return;
    }
    userDao.getChannelCash(channel, function (err,lists) {
        if(err){
            res.send({code:1,info:'参数错误!'});
            return;
        }
        res.send({code:0,lists:lists});

    })
};

/************工具函数****************/

//批量插入
user.batchCreate = function () {
    var ref1 = 'o4AyEt2gypi_z981XBQzM5in0q_U';
    var timer = setInterval(function () {
        var oid = createNonceStr(5);
        userDao.createUser(oid,ref1, function (err) {
            console.log('batchCreate err!');
        })
    },500);

    setTimeout(function () {
        clearInterval(timer);
    },50000);

};


//批量插入
user.batchCreate2 = function () {
    var ref2 = 'o4AyEt2gypi_z981XBQzM5in0q_U';
    var ref1 = '0011223344';

    var timer = setInterval(function () {
        var oid = createNonceStr(5);
        userDao.createUserR1R2(oid,ref1,ref2, function (err) {
            console.log('batchCreateR1R2 err!');
        })
    },800);

    setTimeout(function () {
        clearInterval(timer);
    },80000);

};


//批量插入
user.createCom = function () {
    var oid = 'o4AyEt2gypi_z981XBQzM5in0q_U';


    var timer = setInterval(function () {
        var coin = parseInt(Math.random() * 10 +1);
        var bilno = createNonceStr(15);
        userDao.createCom(oid,bilno,coin, function (err) {

        })
    },800);

    setTimeout(function () {
        clearInterval(timer);
    },80000);

};

user.yzpng = function (req,res) {
    var code = '0123456789';
    var length = 4;
    var randomcode = '';
    for (var i = 0; i < length; i++) {
        randomcode += code[parseInt(Math.random() * 1000) % code.length];
    }

    // 输出图片
    var p = new captchapng(80,30,parseInt(randomcode)); // width,height,numeric captcha
    p.color(255, 255, 255, 0);  // First color: background (red, green, blue, alpha)
    p.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha)
    var img = p.getBase64();
    var imgbase64 = new Buffer(img,'base64');
    fs.writeFile('./public/image/yzm.png', imgbase64, function(err) {
        if(err) {console.log('yzpng...',err)}
    });

    res.send({randomcode:randomcode,img:imgbase64});
};


function createNonceStr(len) {
    return Math.random().toString(36).substr(2, len);
};

module.exports = user;






